/*
 * @Author: 黄达全
 * @Date: 2024-07-20 20:56:53
 * @LastEditTime: 2024-08-05 15:53:37
 */
import axios, { AxiosInstance, AxiosResponse } from "axios"
import type { ApiResponse } from "@/common/type";
import useElementPlus from "@/hooks/useElementPlus"
import { AxiosError } from "axios"
import tool from "@/utils/tool";
import { JwtTokenConstant } from "@/common/constant";
// import router from "@/router";

const { message } = useElementPlus();

// 创建实例
const instance: AxiosInstance = axios.create({
    baseURL: "/api",
    timeout: 3000,
    headers: {
        "Content-Type": "application/json"
    }
})

// 拦截器
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    const token = tool.data.get(JwtTokenConstant.token)
    if (token) {
        config.headers['token'] = token
    }
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use((response: AxiosResponse<ApiResponse<any>>): Promise<AxiosResponse<ApiResponse<any>>> => {
    const data = response.data
    // 错误拦截
    if (data.code == 0) {
        message({
            type: "error",
            message: data.msg
        })
    }
    // 对响应数据做点什么
    return Promise.resolve(response);
}, (error: unknown) => {
    if (error instanceof AxiosError) {
        console.log("错误信息：" + error.message);
    } else {
        console.log('An unexpected error occurred', error);
    }
});


export default instance;